'use strict';
const db = uniCloud.database()
const {
  Base64
} = require("base64")
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event)
  let base = new Base64()
  // 先获取用户信息
  let user = await db.collection("users").where({
    openid: JSON.parse(base.decode(event.openid))
  }).get()
  let res = ''
  // 1表示新增收藏，2表示删除收藏
  if (event.code == 1) {
    user.data[0].collection.unshift(event._id)
    res = await db.collection("users").where({
      openid: JSON.parse(base.decode(event.openid))
    }).update({
      collection: user.data[0].collection
    })
  } else {
    user.data[0].collection = user.data[0].collection.filter(item => item != event._id)
    res = await db.collection("users").where({
      openid: JSON.parse(base.decode(event.openid))
    }).update({
      collection: user.data[0].collection
    })
  }
  //返回数据给客户端
  return res
};
